<!--医院端--订单跟踪--批发采购订单列表--质检 -->
<template>
  <div class="auth-product">
    <el-container class="qualityTesting-box">
      <!-- 列表 -->
      <el-header height="auto">
        <div class="formToptext">
          <el-form
            :inline="true"
            :model="formdata"
            ref="ruleForm"
            label-width="150px" >
            <el-form-item
              v-for="(item,index) in qualityTestingForm"
              :key="index"
              :label="item.title">
              <div
                v-if="item.key === 'status'"
                class="textBox">：{{ statusArr[Number(formdata[item.key])] }}</div>
              <div
                v-else-if="item.key === 'province'"
                class="textBox"
              >
                : {{ formdata.province ? formdata.province : '' }}
                {{ formdata.city===formdata.province ? '' : formdata.city }}
                {{ formdata.area ? formdata.area : '' }}
                {{ formdata.detailedAddress? formdata.detailedAddress : '' }}
              </div>
              <div v-else-if='item.key === "returnNum"'/>
              <div
                v-else
                class="textBox">：{{ formdata[item.key] }}</div>
            </el-form-item>
          </el-form>
        </div>
      </el-header>
      <!-- tab切换 -->
      <tabs
        class="tabs-part"
        :tabs-arr="qualityTestingTabsArr"
        @returnIndex="tabsHandle" />

      <!-- 订单明细列表模块 -->
      <el-editable
        v-if="tabIndex+'' === '1'"
        class="hospital-edit-box"
        :data="getOrderList"
        height="200"
        v-loading="tableLoading"
        :columns="orderTableData"
      >
        <template
          slot-scope="scope"
          slot="default-category"
        >
          {{ category[scope.row.category] }}
        </template>
      </el-editable>
      <!-- 分页模块 -->
      <el-pagination
        v-if="tabIndex+'' === '1'"
        class="pagination"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="detailPage.curPage"
        :page-sizes="PAGE_NUMBER"
        :page-size="detailPage.pageSize"
        :layout="PAGINATION_LAYOUT"
        :total="detailPage.totalElements"
      />
      <!-- 待质检信息列表模块 -->
      <div
        class="formBox"
        v-if="tabIndex+'' === '2'">
        <el-button
          class="submission"
          @click="submission">
          <i class="el-icon-finished"/>
          质检完成</el-button>
        <div
          v-for="(item,index) in getList"
          :key="index">
          <div class="data-info-box">
            <p>发货单号：{{ item.receiveCode }}</p>
            <p>发货时间：{{ item.createdAt }}</p>
            <p>发货数量：{{ item.receiveNumCount }}</p>
          </div>
          <el-editable
            v-if="tabIndex+'' === '2'"
            class="hospital-edit-box"
            :data="item.checkNeedDeliveryList"
            height="200"
            v-loading="tableLoading"
            :columns="qualityTestingTableData"
          >
            <template
              slot="default-returnNum"
              slot-scope="scope"
            >
              <el-input
                v-model.number="scope.row.returnNum"
                @change="changeReturn(scope.row)"/>
            </template>
          </el-editable>
        </div>
      </div>
      <el-dialog
        title="选择入库产品"
        :visible.sync="Visible"
        width="367px"
        class="edit-form">
        <div v-if="objData.qualityTestingNum > 0">
          <div class="dialogDiv">质检未通过数量 {{ objData.qualityTestingNum }} ，品规数 {{ objData.ruleNum }} 种。</div>
          <div class="divtext">系统将自动生成退补单</div>
        </div>
        <div v-else>
          <div class="divtext">质检无异常，确认全部入库。</div>
        </div>
        <div>
          <div class="buttonBox">
            <el-button
              class="submission"
              @click="determine">
              <i class="el-icon-circle-check"/>
              确定</el-button>
            <el-button
              class="cancelsub"
              @click="cancelsub">
              <i class="el-icon-circle-close"/>
              取消</el-button>
          </div>
        </div>
      </el-dialog>
    </el-container>
  </div>
</template>

<script>
import {
  qualityTestingTableData,
  qualityTestingForm, qualityTestingTabsArr, orderTableData, statusArr } from './const'
import SearchForm from '@components/businesscomponents/search'
import { PAGE_NUMBER, PAGINATION_LAYOUT } from '@const/common'
import { hasIn, isObject } from 'lodash'
import {
  attrHospitalNeedOrder,
  attrHospitalNeedOrderItem,
  attrReceiveList,
  attrOrderDetail,
  attrQueryPurchaseList,
  attrOrderWaitDetail,
  attrAddNeedDetailedList,
  attrQueryNeedDetailedList
  ,
  attrGerUserById,
  getScWarehouseEntryRead } from '@const/beforeSettleApi'

import ElEditable from '@components/el-editable'
import tabs from '@components/tabs/index.vue'
export default {
  components: { ElEditable, SearchForm, tabs },
  data () {
    return {
      // tab切换
      qualityTestingTabsArr,
      // 订单状态
      statusArr,
      // 表格Loading
      tableLoading: false,
      // 待质检表头
      qualityTestingTableData,
      // 表格数据
      getList: [],
      // 订单明细表头
      orderTableData,
      // 订单明细数据
      getOrderList: [],
      // 表单编辑默认值
      formdata: {},
      // 表单 详情展示内容-table
      qualityTestingForm,
      // 待质检表单内容
      TestingForm: {},
      // 详情ID
      detailsId: this.$route.query.id,
      // tab切换
      tabIndex: 1,
      // 质检异常
      objData: {
        // 质检未通过数量
        qualityTestingNum: 0,
        // 品规数
        ruleNum: 0
      },
      // 质检异常弹窗
      Visible: false,
      // 产品大类
      category: {
        1: '高值',
        2: '低值',
        3: '试剂',
        4: '设备',
        5: '器械'
      },
      sendTotalNumber: 0, // 总发货数量
      returnList: [], // 质检退回数组
      PAGE_NUMBER, // 页码数组
      PAGINATION_LAYOUT, // 页码功能布局
      detailPage: {
        curPage: 1, // 当前页
        pageSize: PAGE_NUMBER[0], // 一页的数量
        totalElements: 0 // 总共的条数
      },
      awaitTest: {
        curPage: 1, // 当前页
        pageSize: PAGE_NUMBER[0], // 一页的数量
        totalElements: 0 // 总共的条数
      }
    }
  },

  mounted () {
    this.list()
    this.getProductInfo()
    this.waitQualityList()
    let arr = [
      { type: 'button', val: '返回', handle: this.back }
    ]
    const btn = {
      type: 'btn',
      arr: arr
    }
    this.$store.commit('changeLayoutHandle', btn)
  },

  methods: {
    // 点击返回
    back () {
      this.$router.go(-1)
    },

    // 根据地址ID获取联系人
    getUserById () {
      this.$axios({
        method: 'post',
        url: attrGerUserById,
        params: {
          id: this.formdata.receiveAddressId
          // id: 14
        }
      }).then(res => {
        let result = hasIn(res, ['data', 'payload']) ? res.data.payload : {}
        this.formdata = Object.assign(this.formdata, result)

        console.log(this.formdata)
        this.$forceUpdate()
      })
    },

    // 获取产品基本数据
    getProductInfo () {
      console.log(attrReceiveList)
      this.$axios({
        method: 'post',
        url: attrReceiveList,
        data: {
          id: this.$route.query.id
        }
      }).then(res => {
        let result = hasIn(res, ['data', 'payload']) ? res.data.payload : []
        this.formdata = result[0]
        this.getUserById()
      })
    },

    // 获取产品列表
    list () {
      // Loading加载开始
      // 请求列表数据
      this.$axios({
        method: 'post',
        url: attrQueryPurchaseList,
        // url: 'http://47.110.130.245:3000/mock/155/guoke-deepexi-order-center/api/v1/beforeSettle/OcBsNeedOrderItem/queryNeedList',
        data: {
          needOrderId: this.$route.query.id,
          page: 1,
          pageSize: 10
        }
      }).then(res => {
        let result = hasIn(res, ['data', 'payload']) ? res.data.payload.content : []
        this.getOrderList = result.map(item => {
          return item
        })
        this.detailPage.totalElements = res.data.payload.totalElements || 0
      })
    },

    // 待质检信息列表
    waitQualityList () {
      this.$axios({
        method: 'post',
        url: attrQueryNeedDetailedList,
        data: {
          needOrderId: this.$route.query.id
        }
      }).then(res => {
        this.getList = isObject(res.data) ? res.data.payload : []
      })
    },

    // 计算质检不通过的数量
    submission () {
      if (this.getList.length === 0) {
        this.$message({ type: 'warning', message: '暂时没有可质检产品!' })
        return false
      }
      // let ruleNum = 0
      // let qualityTestingNum = 0
      // this.getList.forEach(item => {
      //   qualityTestingNum = Number(qualityTestingNum) + Number(item.checkFailNum)
      //   if (item.checkFailNum > 0) {
      //     ruleNum++
      //   }
      // })
      // this.objData.qualityTestingNum = qualityTestingNum
      // this.objData.ruleNum = ruleNum
      let ruleNum = 0
      let qualityTestingNum = 0
      this.returnList.forEach(item => {
        if (item.checkAbnormalCount > 0) {
          ruleNum += 1
          qualityTestingNum += item.checkAbnormalCount
        }
      })

      this.objData.qualityTestingNum = qualityTestingNum
      this.objData.ruleNum = ruleNum
      this.Visible = true
    },

    // 质检确定
    determine () {
      let arr = []
      for (let i = 0; i < this.getList.length; i++) {
        for (let j = 0; j < this.getList[i].checkNeedDeliveryList.length; j++) {
          if (Number(this.getList[i].checkNeedDeliveryList[j].returnNum) !== 0) {
            let obj = {
              orderItemId: this.getList[i].checkNeedDeliveryList[j].id,
              checkAbnormalCount: this.getList[i].checkNeedDeliveryList[j].returnNum
            }
            arr.push(obj)
          }
        }
      }

      let data = {
        needOrderId: this.$route.query.id,
        finishCheckList: arr
      }
      this.$axios({
        method: 'post',
        url: attrAddNeedDetailedList,
        data: data
      }).then(res => {
        this.Visible = false
        this.$message({
          type: 'success',
          message: '已质检'
        })
        this.$router.go(-1)
      })
    },

    // 质检取消
    cancelsub () {
      this.Visible = false
    },

    // tab切换
    tabsHandle (index) {
      this.tabIndex = this.qualityTestingTabsArr[index].val
    },

    // 质检异常数量改变
    changeReturn (val) {
      let pattern = new RegExp(/^\d{1,}$/)
      if (pattern.test(val.returnNum)) {
        if (val.returnNum <= val.receiveNum) {
          if (this.returnList.length > 0) {
            this.returnList.forEach(item => {
              if (item.orderItemId === val.orderItemId) {
                return (item.checkAbnormalCount = val.returnNum)
              } else {
                this.returnList.push({
                  orderId: this.$route.query.id,
                  checkAbnormalCount: val.returnNum,
                  orderItemId: val.orderItemId
                })
              }
            })
          } else {
            this.returnList.push({
              orderId: this.$route.query.id,
              checkAbnormalCount: val.returnNum,
              orderItemId: val.orderItemId
            })
          }
        } else {
          this.$message({
            type: 'error',
            message: '退回数量不能大于发货数量'
          })
        }
      } else {
        this.$message({
          type: 'error',
          message: '请输入数字'
        })
      }
    },

    // 页码更改
    handleSizeChange (size) {
      if (this.tabIndex === 1) {
        this.detailPage.pageSize = size
        this.list()
      }
      if (this.tabIndex === 2) {
        this.awaitTest.pageSize = size
        this.waitQualityList()
      }
    },

    // 切换不一样的页面,重置一切数据
    handleCurrentChange (curPage) {
      if (this.tabIndex === 1) {
        this.detailPage.curPage = curPage
        this.list()
      }
      if (this.tabIndex === 2) {
        this.awaitTest.curPage = curPage
        this.waitQualityList()
      }
    }
  }
}
</script>

<style lang="less">
.qualityTesting-box {
  height: 100%;
  overflow: auto;
  .data-info-box {
    display: flex;
    p {
      margin-right: 30px;
      margin-bottom: 10px;
      margin-top: 10px;
    }
  }
  .formBox {
    width: 100%;

    .qualityTestingForm {
      display: flex;
      width: 1000px;
      float: left;

      .from-item {
        width: 300px;
      }
    }

    .submissionBox {
      float: right;
      margin-right: 10px;

      .submission {
        background: rgba(35, 113, 197, 1);
        border: 0;
        color: #fff;
        margin-bottom: 10px;
      }
    }
  }

  .topInput {
    width: 211px;
  }

  .pagination {
    padding-top: 10px;
    display: flex;
    justify-content: flex-end;
    padding-right: 0;
  }

  .formToptext {
    margin-bottom: 20px;

    .el-form-item {
      margin-right: 16px;
      margin-bottom: 16px;

      .textBox {
        width: 220px;
      }
    }

    .el-form-item__label {
      padding-right: 10px;
    }
  }

  .buttonBox {
    width: 197px;
    margin: 0 auto;
  }

  .dialogDiv {
    text-align: center;
    margin-bottom: 20px;
  }

  .divtext {
    text-align: center;
    margin-top: 10px;
    margin-bottom: 10px;
  }

  .submission {
    background: rgba(35, 113, 197, 1);
    border: 0;
    color: #fff;
    margin-bottom: 10px;
  }
}
</style>
